/**
 * ReportGear(2011)
 */
package com.reportgear.report.model.calculator;

import java.util.Iterator;

import com.reportgear.report.model.ReportModel;
import com.reportgear.report.model.cell.Cell;
import com.reportgear.report.model.cell.value.CrossDocDataObject;

/**
 * 
 * 交叉档案数据分组计算
 * 
 * @version 1.0 2011-4-10
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
public class CrossDocDataObjectValueGroupCalculator extends AbstractCalculator {
	public CrossDocDataObjectValueGroupCalculator() {

	}

	@Override
	public ReportModel calculate(ReportModel model, CalcParameter parameter) {
		if (logger.isDebugEnabled()) {
			logger.debug("计算模型：薪酬档案分组计算");
		}

		ReportModel calcModel = model;

		if (parameter.getGroupLevel() <= 0) {
			return calcModel;
		}

		Iterator<Cell> cells = calcModel.getCellsIteratorByCellElementClass(CrossDocDataObject.class);
		for (Iterator<Cell> i = cells; i.hasNext();) {
			Cell cell = i.next();

			CrossDocDataObject value = (CrossDocDataObject) cell.getValue();

			if ("deptName".equals(value.getField())) {
				// 如果上一个也是deptName则比较分组
				int row = cell.getRow();

				if (row > 0) {
					int col = cell.getColumn();
					Cell prev = calcModel.getCell(col, row - 1);
					Object prevValue = prev.getValue();

					if (prevValue instanceof CrossDocDataObject) {
						CrossDocDataObject cddo = (CrossDocDataObject) prevValue;
						if ("deptName".equals(cddo.getField())) {
							String cv = cddo.getValue();
							if (cv != null && !cv.equals(value.getValue())) {
								model.getRowPropList().setGroup(row, true);
							}
						}
					}
				}
			}
		}

		return calcModel;
	}
}
